#include "stm32f10x.h"                  // Device header

void Encoder_Init(void)
{
	//开启时钟
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
	//因为定时器后续会被编码器接管，不需要配置时钟源
	
	//初始化GPIO
	GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;				//上拉输入
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA, &GPIO_InitStructure);
	
	//初始化时基单元
	TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
	TIM_TimeBaseStructInit(&TIM_TimeBaseInitStructure);
	TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
	TIM_TimeBaseInitStructure.TIM_Period = 65536 - 1;			//重装值给最大
	TIM_TimeBaseInitStructure.TIM_Prescaler = 1 - 1;			//不分频
	TIM_TimeBaseInit(TIM3, &TIM_TimeBaseInitStructure);
	
	//编码器初始化
	//输入捕获部分
	TIM_ICInitTypeDef TIM_ICInitStructure;
	TIM_ICStructInit(&TIM_ICInitStructure);
	
	TIM_ICInitStructure.TIM_Channel = TIM_Channel_1;				//通道
	TIM_ICInitStructure.TIM_ICFilter = 0xF;							//滤波器
	TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising;		//触发方式，上升沿...
	TIM_ICInit(TIM3, &TIM_ICInitStructure);
	
	TIM_ICInitStructure.TIM_Channel = TIM_Channel_2;				//通道
	TIM_ICInitStructure.TIM_ICFilter = 0xF;							//滤波器
	TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising;		//触发方式，上升沿...
	TIM_ICInit(TIM3, &TIM_ICInitStructure);
	
	//编码器接口配置
	//第二种参数是有效边沿   三四参数是触发方式，上升沿...
	TIM_EncoderInterfaceConfig(TIM3, TIM_EncoderMode_TI12, TIM_ICPolarity_Rising, TIM_ICPolarity_Rising);
	
	//开启时钟
	TIM_Cmd(TIM3, ENABLE);
}

/**
  * @brief		获取编码器计数
  * @parm			无
  * @retval		计数，将无符号直接转为有符号
  */
int16_t Encoder_GetCounter(void)
{
	return TIM_GetCounter(TIM3);
}

/**
  * @brief		获取一定时间编码器计数
  * @parm			无
  * @retval		计数，将无符号直接转为有符号
  */
int16_t Encoder_GetSpeed(void)
{
	int16_t Temp = TIM_GetCounter(TIM3);
	TIM_SetCounter(TIM3, 0);
	return Temp;
}
